{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# `int8_t`（或 `std::int8_t`）类型的取值范围是多少？为什么？\n",
    "\n",
    "**范围**：`[-128, 127]`。\n",
    "\n",
    "**原因**：`int8_t` 是精确 8 位的有符号整数（以二补码存储）。8 位能表达 $2^8 = 256$ 个数，按二补码分布为 $[-2^{7}, 2^{7}-1]$。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "vscode": {
     "languageId": "cpp"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "int8_t min = -128\n",
      "int8_t max = 127\n"
     ]
    }
   ],
   "source": [
    "#include <cstdint>\n",
    "#include <limits>\n",
    "#include <iostream>\n",
    "\n",
    "{\n",
    "    std::cout << \"int8_t min = \"\n",
    "              << static_cast<int>(std::numeric_limits<int8_t>::min())\n",
    "              << \"\\nint8_t max = \"\n",
    "              << static_cast<int>(std::numeric_limits<int8_t>::max())\n",
    "              << '\\n';\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# `uint8_t` 与 `unsigned char` 的关系及输出\n",
    "\n",
    "- 通常 `uint8_t` 是 `unsigned char` 的别名；输出时需转成整型以避免按字符显示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "vscode": {
     "languageId": "cpp"
    }
   },
   "outputs": [],
   "source": [
    "// https://godbolt.org/z/9fhfef7a1 x86\n",
    "// https://godbolt.org/z/a938hMhxa arm64\n",
    "\n",
    "#include <cstdint>\n",
    "#include <type_traits>\n",
    "#include <iostream>\n",
    "\n",
    "int main() {\n",
    "    std::cout << std::boolalpha\n",
    "              << \"uint8_t is unsigned char: \"\n",
    "              << std::is_same<uint8_t, unsigned char>::value << '\\n';\n",
    "\n",
    "    uint8_t u = 200;\n",
    "    std::cout << \"Raw cout (as char): \" << u << '\\n';\n",
    "    std::cout << \"As number: \" << static_cast<int>(u) << '\\n';\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# `double` 转 `int` 的截断与越界\n",
    "\n",
    "- 转换规则为朝零截断；若结果超出 `int` 能表示的范围则行为未定义。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "vscode": {
     "languageId": "cpp"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "static_cast<int>(3.9)  = 3\n",
      "static_cast<int>(-3.9) = -3\n",
      "static_cast<int>(1e40) (UB) = -2147483648\n"
     ]
    }
   ],
   "source": [
    "#include <iostream>\n",
    "\n",
    "{\n",
    "    double a = 3.9;\n",
    "    double b = -3.9;\n",
    "    std::cout << \"static_cast<int>(3.9)  = \" << static_cast<int>(a) << '\\n';\n",
    "    std::cout << \"static_cast<int>(-3.9) = \" << static_cast<int>(b) << '\\n';\n",
    "\n",
    "    double huge = 1e40; // 超范围 => UB（示例，不可依赖其结果）\n",
    "    int x = static_cast<int>(huge);\n",
    "    std::cout << \"static_cast<int>(1e40) (UB) = \" << x << '\\n';\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# `sizeof(bool)` 不一定是 1 字节\n",
    "\n",
    "- C++ 仅要求 `sizeof(bool) >= 1`，实际大小由 ABI 决定。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "vscode": {
     "languageId": "cpp"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sizeof(bool) = 1 byte(s)\n"
     ]
    }
   ],
   "source": [
    "// https://godbolt.org/z/q4Ye7rzs1\n",
    "// https://godbolt.org/z/a938hMhxa\n",
    "\n",
    "#include <iostream>\n",
    "\n",
    "{\n",
    "    std::cout << \"sizeof(bool) = \" << sizeof(bool) << \" byte(s)\\n\";\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# `alignof` 与结构体对齐\n",
    "\n",
    "- `alignof` 返回类型的对齐要求，可配合 `offsetof` 观察成员布局。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "vscode": {
     "languageId": "c++"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "alignof(Example) = 8\n",
      "offsetof(c) = 0\n",
      "offsetof(i) = 4\n",
      "offsetof(d) = 8\n",
      "sizeof(Example) = 16\n"
     ]
    }
   ],
   "source": [
    "#include <cstddef>\n",
    "#include <iostream>\n",
    "\n",
    "struct Example {\n",
    "    char  c;\n",
    "    int   i;\n",
    "    double d;\n",
    "};\n",
    "\n",
    "{\n",
    "    std::cout << \"alignof(Example) = \" << alignof(Example) << '\\n';\n",
    "    std::cout << \"offsetof(c) = \" << offsetof(Example, c) << '\\n';\n",
    "    std::cout << \"offsetof(i) = \" << offsetof(Example, i) << '\\n';\n",
    "    std::cout << \"offsetof(d) = \" << offsetof(Example, d) << '\\n';\n",
    "    std::cout << \"sizeof(Example) = \" << sizeof(Example) << '\\n';\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 严格别名（strict aliasing）规则\n",
    "\n",
    "- 规则：对象应通过其实际类型或允许的别名类型访问；违规会导致未定义行为。\n",
    "- 合法做法：使用 `std::memcpy` 或 `std::bit_cast`（C++20）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "vscode": {
     "languageId": "c++"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Safe reinterpretation via memcpy: 1\n",
      "Strict aliasing UB example: 5.88545e-44\n"
     ]
    }
   ],
   "source": [
    "#include <cstring>\n",
    "#include <iostream>\n",
    "\n",
    "{\n",
    "    int value = 0x3f800000;\n",
    "    float fSafe;\n",
    "    std::memcpy(&fSafe, &value, sizeof(fSafe));\n",
    "    std::cout << \"Safe reinterpretation via memcpy: \" << fSafe << '\\n';\n",
    "\n",
    "    // 严格别名违规示例（UB）：\n",
    "    int x = 42;\n",
    "    float* pf = reinterpret_cast<float*>(&x);\n",
    "    std::cout << \"Strict aliasing UB example: \" << *pf << '\\n';\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# POD vs 标准布局与非 POD 示例\n",
    "\n",
    "- **标准布局**：保证内存布局可与 C 兼容。\n",
    "- **POD**：既是标准布局又是平凡类型（构造/析构等均平凡）。\n",
    "- 含自定义析构或虚函数会破坏平凡性，从而不是 POD。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "vscode": {
     "languageId": "c++"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Plain is standard layout: true\n",
      "Plain is POD: true\n",
      "NonPOD is standard layout: true\n",
      "NonPOD is POD: false\n"
     ]
    }
   ],
   "source": [
    "#include <type_traits>\n",
    "#include <iostream>\n",
    "\n",
    "struct Plain {\n",
    "    int x;\n",
    "    double y;\n",
    "};\n",
    "\n",
    "struct NonPOD {\n",
    "    ~NonPOD() {}   // 非平凡析构 => 不是 POD\n",
    "    int x;\n",
    "};\n",
    "\n",
    "{\n",
    "    std::cout << std::boolalpha;\n",
    "    std::cout << \"Plain is standard layout: \"\n",
    "              << std::is_standard_layout<Plain>::value << '\\n';\n",
    "    std::cout << \"Plain is POD: \"\n",
    "              << std::is_pod<Plain>::value << '\\n';\n",
    "    std::cout << \"NonPOD is standard layout: \"\n",
    "              << std::is_standard_layout<NonPOD>::value << '\\n';\n",
    "    std::cout << \"NonPOD is POD: \"\n",
    "              << std::is_pod<NonPOD>::value << '\\n';\n",
    "}"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "C++17",
   "language": "C++17",
   "name": "xcpp17"
  },
  "language_info": {
   "codemirror_mode": "text/x-c++src",
   "file_extension": ".cpp",
   "mimetype": "text/x-c++src",
   "name": "C++17",
   "version": "11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
